package cn.wenhe9.novel.manager;

import cn.wenhe9.novel.constant.CacheConsts;
import cn.wenhe9.novel.constant.DatabaseConsts;
import cn.wenhe9.novel.domain.dto.BookCategoryDto;
import cn.wenhe9.novel.domain.dto.UserFeedbackDto;
import cn.wenhe9.novel.domain.dto.UserInfoDto;
import cn.wenhe9.novel.domain.entity.book.BookCategory;
import cn.wenhe9.novel.domain.entity.user.UserFeedback;
import cn.wenhe9.novel.domain.entity.user.UserInfo;
import cn.wenhe9.novel.domain.vo.PageQueryVo;
import cn.wenhe9.novel.mapper.UserFeedbackMapper;
import cn.wenhe9.novel.result.PageResultDto;
import cn.wenhe9.novel.result.ResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author DuJinliang
 * 2022/5/27
 */
@Component
public class UserFeedbackCacheManager {
    @Resource
    private UserFeedbackMapper userFeedbackMapper;

    /**
     * 查询用户信息，并放入缓存中
     */
    @Cacheable(
            value = CacheConsts.USER_FEEDBACK_CACHE_NAME,
            cacheManager = CacheConsts.REDIS_CACHE_MANAGER
//            keyGenerator = "keyGenerator"
    )
    public PageResultDto<UserFeedbackDto> listFeedback(Long userId, Long page, Long limit) {
        QueryWrapper<UserFeedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConsts.UserFeedBackTable.COLUMN_USER_ID, userId);
        Page<UserFeedback> feedbackPage = userFeedbackMapper.selectPage(new Page<>(page, limit), queryWrapper);
        List<UserFeedbackDto> feedbackDtoList = feedbackPage.getRecords().stream().map(item ->
                UserFeedbackDto.builder()
                        .content(item.getContent())
                        .createTime(item.getCreateTime())
                        .build()).collect(Collectors.toList());
        return PageResultDto.of(page, limit, feedbackPage.getTotal(), feedbackDtoList);
    }

    @CacheEvict(
            value = CacheConsts.USER_FEEDBACK_CACHE_NAME,
            cacheManager = CacheConsts.REDIS_CACHE_MANAGER,
            allEntries = true
//            keyGenerator = "keyGenerator"
    )
    public ResultResponse<Void> saveFeedback(Long userId, String content) {
        UserFeedback userFeedback = new UserFeedback();
        userFeedback.setUserId(userId);
        userFeedback.setContent(content);
        userFeedback.setCreateTime(LocalDateTime.now());
        userFeedback.setUpdateTime(LocalDateTime.now());
        userFeedbackMapper.insert(userFeedback);
        return ResultResponse.ok();
    }
}
